package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;

@Slf4j
@Service
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {


    //静态化
    @Autowired
    private Configuration configuration;

    @Autowired
    ApArticleContentMapper articleContentMapper;

    @Autowired
    FileStorageService fileStorageService;

    @Autowired
    ApArticleMapper apArticleMapper;

    @Override
    @Async
    public void buildArticleToMinIO(ApArticle apArticle, String content) throws Exception {

        Template template = configuration.getTemplate("article.ftl");


        if(StringUtils.isNotBlank(content)){

            //字符串转对象
            JSONArray jsonList = JSON.parseArray(content);

            //第一个参数 数据模型
            //第二个参数  输出流
            HashMap<Object, Object> dataModel = new HashMap<>();
            dataModel.put("content",jsonList);

            StringWriter out = new StringWriter();
            template.process(dataModel, out);


            //minio
            ByteArrayInputStream inputStream = new ByteArrayInputStream(out.toString().getBytes());
            String uploadHtmlFile = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", inputStream);

            //文件地址保存
            apArticle.setStaticUrl(uploadHtmlFile);
            apArticleMapper.updateById(apArticle);

            //同步数据到es
            addArcileToEs(apArticle,content);
        }

    }

    //方案1
    @Autowired
    RestHighLevelClient restHighLevelClient;
    private void addArcileToEs(ApArticle apArticle, String content) {
        SearchArticleVo vo =new SearchArticleVo();
        vo.setContent(content);
        BeanUtils.copyProperties(apArticle,vo);
        IndexRequest indexRequest = new IndexRequest("app_info_article").id(vo.getId().toString()).
                source(JSON.toJSONString(vo),XContentType.JSON);
        try {
            restHighLevelClient.index(indexRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("同步数据失败",e.getMessage());
           // e.printStackTrace();
        }
    }






//    @Autowired
//    方案2
//    private KafkaTemplate<String,String> kafkaTemplate;
//
//    /**
//     * 送消息，创建索引
//     * @param apArticle
//     * @param content
//     * @param path
//     */
//    private void createArticleESIndex(ApArticle apArticle, String content, String path) {
//        SearchArticleVo vo = new SearchArticleVo();
//        BeanUtils.copyProperties(apArticle,vo);
//        vo.setContent(content);
//        vo.setStaticUrl(path);
//
//        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(vo));
//    }
}
